<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告 -->
      <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex - 0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左侧tabs栏 -->
      <!-- 把一个表单拆成多个部分 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-position="top">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave='beforeTabLeave' @tab-click='tabClick'>
          <!-- 步骤一 基本信息填写 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type='number'></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type='number'></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type='number'></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" clearable @change="handleChange"
                :props="{ expandTrigger: 'hover' , label:'cat_name' , value:'cat_id'}">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 步骤二 添加商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="obj in manyTableData" :key="obj.attr_id" :label="obj.attr_name">
              <!-- 多选框 -->
              <el-checkbox-group v-model="obj.attr_vals">
                <el-checkbox :label="item" v-for="(item,i) in obj.attr_vals1" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 步骤三 添加商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 步骤四 上传图片 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- action 把图片上传到指定服务器 -->
            <el-upload action="http://42.192.71.221:8889/api/private/v1/upload" :on-preview="handlePreview"
              :on-remove="handleRemove" list-type="picture" :headers='headersObj' :on-success='handleSuccess'>
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <!-- 步骤五 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" style="margin:15px 0" @click="addGood">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="picDialogVisible" width="30%">
      <img style="width:100%" :src="imgUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
// 解构引入lodash方法
import { cloneDeep } from 'lodash'
export default {
  data () {
    return {
      // 设置上传的请求头部参数
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 商品属性
      onlyTableData: [],
      // 商品参数
      manyTableData: [],
      // 商品分类数据
      cateList: [],
      // 当前是第几个步骤
      activeIndex: '0',
      // 添加商品表单的内容
      addForm: {
        goods_name: '商品名称',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 用户选择数据
        goods_cat: [1, 3, 6],
        // 图片上传参数
        pics: [],
        // 富文本介绍内容
        goods_introduce: ''
      },
      // 添加商品表单的规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 控制图片预览对话框显示隐藏
      picDialogVisible: false,
      // 预览图片地址
      imgUrl: ''
    }
  },
  methods: {
    // 添加商品
    addGood () {
      this.$refs.addFormRef.validate(async bool => {
        if (!bool) return this.$message.error('请填写表单必填项')
        // 深拷贝区分渲染页面的数据和传给服务器的数据
        const form = cloneDeep(this.addForm)
        // 把给后台的表单数据处理成字符串
        form.goods_cat = form.goods_cat.join(',')
        // 商品动态参数和静态属性
        form.attrs = []
        // 动态参数
        this.manyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          })
        })
        // 静态属性
        this.onlyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功')
        // this.$router.push('/goods')
        this.$router.go(-1)
      })
    },
    // 文件上传成功时的钩子
    handleSuccess (response) {
      // 和商品信息关联 把图片存到表单中
      this.addForm.pics.push({
        pic: response.data.tmp_path
      })
    },
    // 文件列表移除文件时的钩子
    handleRemove (file) {
      // 解构
      const { response: { data } } = file
      // 获取要删除图片的临时路径
      const filePath = data.tmp_path
      // 获取要删除图片的索引
      const i = this.addForm.pics.findIndex(item => item.pic === filePath)
      // 根据索引删除对应项
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm.pics)
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview ({ response: { data } }) {
      this.imgUrl = `http://42.192.71.221:8889/${data.tmp_path}`
      this.picDialogVisible = true
    },
    // tab页签点击事件
    async tabClick () {
      if (this.activeIndex === '1') { // 访问的是商品参数页签
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) return this.$message.error('获取商品参数失败')
        res.data.forEach(ele => {
          // 避免取消选中数据就从页面消失 attr_vals负责操作attr_vals1负责渲染
          ele.attr_vals1 = ele.attr_vals = ele.attr_vals.length === 0 ? [] : ele.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') { // 访问的是商品属性页签
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) return this.$message.error('获取商品属性失败')
        this.onlyTableData = res.data
      }
    },
    // 监听tabs切换
    beforeTabLeave (newActiveName, oldActiveName) {
      if (this.addForm.goods_name.length === 0) {
        this.$message.error('请输入商品名称')
        return false
      }
      if (this.addForm.goods_cat.length !== 3 && oldActiveName === '0') {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // 监听级联选择器改变
    handleChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择三级分类')
        this.addForm.goods_cat = []
      }
    },
    // 获取商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类数据失败')
      this.cateList = res.data
    }
  },
  computed: {
    // 选中三级分类id
    cateId () {
      return this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
    }
  },
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getCateList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
/deep/ .ql-editor {
  height: 240px;
}
</style>
